<?php
require_once 'LoanProducts.php';

class Loan_CalculatorController extends Zend_Controller_Action
{
    public $contexts = array('browse' => array('xml'));
    public function init() {}
    
    public function indexAction()
    {
        $this->view->form = new Emms_Form_Loan_Calculator();
        if ($this->getRequest()->isPost()) {
            if ($this->view->form->isValid($this->getRequest()->getPost())) {
                /* Form valid */
                $values = $this->view->form->getValues();
                try {
                    switch($values['InterestCalculation']) {
                        case 'Declining': $plan = new Emms_PmtPlan(new Emms_Loan($values)); break;
                        case 'Flat': $plan = new Emms_PmtPlanFlat(new Emms_Loan($values)); break;
                    }
                    $this->_helper->Cache->save(array('form' => $values, 'plan' => $plan->toArray()), 'loan_calculator_plan');
                    $this->view->plan = true;
                } catch (Exception $e)  {
                    $this->view->form->setDescription($this->view->form->translate($e->getMessage()));
                }
            } else { 
                $this->view->form->setDescription($this->view->form->translate("Operation can't be completed. Please check the form and try again."));
            }  
        }
        $this->_helper->layout->setLayout('form');
    }
    
    public function planAction()
    {
        $cache = $this->_helper->Cache->load('loan_calculator_plan');
        $this->view->plan = $cache['plan'];
        $this->view->form = $cache['form'];
        $this->view->title = $this->view->translate('Financial calculator');
        $this->view->description = $this->view->translate('Payment plan');
        $this->_helper->layout->setLayout('view');
    }
}
